package com.vehiclemanagement.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vehiclemanagement.entity.TrafficViolation;
import com.vehiclemanagement.mapper.TrafficViolationMapper;
import com.vehiclemanagement.service.TrafficViolationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.Year;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 交通违章记录服务实现类
 */
@Service
@Slf4j
public class TrafficViolationServiceImpl extends ServiceImpl<TrafficViolationMapper, TrafficViolation> implements TrafficViolationService {

    @Autowired
    private TrafficViolationMapper trafficViolationMapper;

    @Override
    public IPage<TrafficViolation> pageViolations(Integer current, Integer size, String searchTerm,
                                                 Long vehicleId, Long driverId, String violationType,
                                                 Integer status, LocalDateTime startTime, LocalDateTime endTime) {
        Page<TrafficViolation> page = new Page<>(current, size);
        StringBuilder whereSql = new StringBuilder();
        whereSql.append(" v.del_flag = 0 ");

        if (StringUtils.hasText(searchTerm)) {
            whereSql.append(" AND (ve.plate_number LIKE '%").append(searchTerm).append("%'")
                    .append(" OR d.name LIKE '%").append(searchTerm).append("%'")
                    .append(" OR v.violation_location LIKE '%").append(searchTerm).append("%')");
        }

        if (vehicleId != null) {
            whereSql.append(" AND v.vehicle_id = ").append(vehicleId);
        }

        if (driverId != null) {
            whereSql.append(" AND v.driver_id = ").append(driverId);
        }

        if (StringUtils.hasText(violationType)) {
            whereSql.append(" AND v.violation_type = '").append(violationType).append("'");
        }

        if (status != null) {
            whereSql.append(" AND v.status = ").append(status);
        }

        if (startTime != null) {
            whereSql.append(" AND v.violation_time >= '").append(startTime).append("'");
        }

        if (endTime != null) {
            whereSql.append(" AND v.violation_time <= '").append(endTime).append("'");
        }

        return trafficViolationMapper.selectPageWithInfo(page, whereSql.toString());
    }

    @Override
    public TrafficViolation getViolationById(Long id) {
        TrafficViolation violation = getById(id);
        if (violation == null) {
            log.error("交通违章记录不存在, id: {}", id);
            return null;
        }
        return violation;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addViolation(TrafficViolation violation) {
        if (violation == null) {
            log.error("添加交通违章记录失败: violation不能为空");
            return false;
        }

        // 设置默认值
        violation.setCreateTime(LocalDateTime.now());
        violation.setUpdateTime(LocalDateTime.now());
        violation.setDelFlag(0);
        
        // 默认状态为未处理
        if (violation.getStatus() == null) {
            violation.setStatus(0);
        }

        boolean result = save(violation);
        log.info("添加交通违章记录 {} ", result ? "成功" : "失败");
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateViolation(TrafficViolation violation) {
        if (violation == null || violation.getId() == null) {
            log.error("更新交通违章记录失败: violation或ID不能为空");
            return false;
        }

        violation.setUpdateTime(LocalDateTime.now());
        boolean result = updateById(violation);
        log.info("更新交通违章记录 {} , id: {}", result ? "成功" : "失败", violation.getId());
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteViolation(Long id) {
        if (id == null) {
            log.error("删除交通违章记录失败: ID不能为空");
            return false;
        }

        int result = trafficViolationMapper.deletePhysically(id);
        log.info("删除交通违章记录 {} , id: {}", result > 0 ? "成功" : "失败", id);
        return result > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean handleViolation(Long id, String handler, String handlingMethod, String remark) {
        if (id == null) {
            log.error("处理交通违章记录失败: ID不能为空");
            return false;
        }

        TrafficViolation violation = getById(id);
        if (violation == null) {
            log.error("处理交通违章记录失败: 记录不存在, id: {}", id);
            return false;
        }

        // 更新处理信息
        violation.setHandler(handler);
        violation.setHandlingMethod(handlingMethod);
        violation.setHandlingTime(LocalDateTime.now());
        violation.setRemark(remark);
        violation.setStatus(1); // 已处理
        violation.setUpdateTime(LocalDateTime.now());

        boolean result = updateById(violation);
        log.info("处理交通违章记录 {} , id: {}", result ? "成功" : "失败", id);
        return result;
    }

    @Override
    public BigDecimal sumFineAmountByVehicleId(Long vehicleId) {
        if (vehicleId == null) {
            log.error("计算车辆累计罚款金额失败: vehicleId不能为空");
            return BigDecimal.ZERO;
        }
        BigDecimal sum = trafficViolationMapper.sumFineAmountByVehicleId(vehicleId);
        return sum == null ? BigDecimal.ZERO : sum;
    }

    @Override
    public BigDecimal sumFineAmountByDriverId(Long driverId) {
        if (driverId == null) {
            log.error("计算驾驶员累计罚款金额失败: driverId不能为空");
            return BigDecimal.ZERO;
        }
        BigDecimal sum = trafficViolationMapper.sumFineAmountByDriverId(driverId);
        return sum == null ? BigDecimal.ZERO : sum;
    }

    @Override
    public Integer sumPointDeductionByVehicleId(Long vehicleId) {
        if (vehicleId == null) {
            log.error("计算车辆累计扣分失败: vehicleId不能为空");
            return 0;
        }
        Integer sum = trafficViolationMapper.sumPointDeductionByVehicleId(vehicleId);
        return sum == null ? 0 : sum;
    }

    @Override
    public Integer sumPointDeductionByDriverId(Long driverId) {
        if (driverId == null) {
            log.error("计算驾驶员累计扣分失败: driverId不能为空");
            return 0;
        }
        Integer sum = trafficViolationMapper.sumPointDeductionByDriverId(driverId);
        return sum == null ? 0 : sum;
    }

    @Override
    public List<Map<String, Object>> statisticsByMonth(Integer year) {
        if (year == null) {
            // 默认使用当前年份
            year = LocalDateTime.now().getYear();
        }
        
        LocalDateTime startTime = LocalDateTime.of(year, 1, 1, 0, 0, 0);
        LocalDateTime endTime = LocalDateTime.of(year, 12, 31, 23, 59, 59);
        
        return trafficViolationMapper.statisticsByMonth(startTime, endTime);
    }

    @Override
    public List<Map<String, Object>> statisticsByViolationType() {
        return trafficViolationMapper.statisticsByViolationType();
    }
} 